#!/usr/bin/env python
# encoding: utf-8
"""
@author: guihehans
@file: zeus_api.py
@time: 2020/7/8 14:33
@function:
this is the api to access zeus info.

"""
import sys

import pandas

from jenkins_tool.common import sql_mapping, const, EnhanceUtills
from jenkins_tool.common.SYSDBUtils import Mysql_DB
from jenkins_tool.log import Logger
import requests

module_name = "zeus_info"
system_id = const.SYS_ID
global logger
logger = Logger.Logger(clevel=const.Logging_command_level, Flevel=const.Logging_file_level)


def get_deploy_info_by_sysid(sys_id: str, env: str) -> dict:
    """
    get the deploy information by the sys_id(e.g, ld139) and environment.
    using web query api.

    :param sys_id:
    :param env: the deploy environment(e.g,"pre").see more in const.ZEUS_ENV
    :return: dict. a dict object contains deploy info.
    """

    try:
        env_code = const.ZEUS_ENV.get(env)
        zeus_deploy_api_url = const.ZEUS_QUERY_API_URL.format(sys_id, env_code)
        logger.info(module_name, sys._getframe().f_code.co_name,
                    "start querying zeus api:{}".format(zeus_deploy_api_url)
                    , system_id
                    )

        url = zeus_deploy_api_url
        response = requests.get(url, headers={})
        result_list = response.json()['list']
        sorted_result_list = sort_by_ip_suffix(result_list)
        return sorted_result_list
    except Exception as e:
        logger.error(module_name, sys._getframe().f_code.co_name, EnhanceUtills.traceback_printer(),
                     system_id)


def sort_by_ip_suffix(data_list):
    """
    sort the data by the the last segment of ip columns.

    :param data_list:
    :return:
    """
    key_value_dict = {}
    sorted_data_list = []
    for data in data_list:
        try:
            last_segment_ip = int(data['sysName'].split(".")[3])
            key_value_dict[last_segment_ip] = data
        # the sysName is null, skip it
        except:
            continue

    for key in sorted(key_value_dict):
        sorted_data_list.append(key_value_dict[key])
    return sorted_data_list


if __name__ == '__main__':
    sys_id = "ld139"
    env = "prod"
    result = get_deploy_info_by_sysid(sys_id, env)
    print(result)
    print(sort_by_ip_suffix(result))
    # for i, value in enumerate(result):
    #     print(value)
    # df = pandas.DataFrame(result)
    # print(df)
